package com.doge.walknovel.business.home.profile.wallet

import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.activity.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.doge.wnpro.R
import com.doge.walknovel.core.BaseActivity
import com.doge.walknovel.core.account.AccountHelper
import com.doge.walknovel.core.account.AppUserViewModel
import com.doge.walknovel.core.base.isRefreshing
import com.doge.wnpro.databinding.ActivityWalletHistoryBinding
import com.doge.walknovel.payment.google.AppBillingClientLifecycle

class WalletHistoryActivity : BaseActivity() {
    private val binding by lazy { ActivityWalletHistoryBinding.inflate(layoutInflater) }
    private val appBillingClient by lazy { AppBillingClientLifecycle.get() }
    private val viewModel: WalletHistoryViewModel by viewModels { WalletHistoryViewModelFactory() }
    private val adapter by lazy { WalletHistoryAdapter() }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
        AppUserViewModel.get().requestSelfInfo()
        AccountHelper.selfInfo.observe(this) {
            binding.total.text =
                String.format(getString(R.string.total_coins_xxx), (it?.coinNum ?: 0).toString())
        }
        binding.refreshLayout.setColorSchemeResources(R.color.pull_refresh)
        binding.refreshLayout.setOnRefreshListener {
            viewModel.request()
        }
        binding.recyclerView.itemAnimator = null
        binding.recyclerView.layoutManager = LinearLayoutManager(binding.recyclerView.context)
        binding.recyclerView.adapter = adapter

        appBillingClient.setup(lifecycle, refer = null, silently = true)
        viewModel.loading.observe(this) {
            binding.refreshLayout.isRefreshing = it.isRefreshing()
        }
        viewModel.dataList.observe(this) {
            adapter.submitList(it)
        }
        viewModel.request()
    }

    companion object {
        fun start(context: Context) {
            AccountHelper.requiredLogin {
                context.startActivity(Intent(context, WalletHistoryActivity::class.java))
            }
        }
    }
}